<template>
    <el-container style="background-color: #202124;">
        <transition appear name="animate__animated animate__fadeIn" enter-active-class="animate__fadeIn">
            <el-container id="container">
                <el-main style="flex-basis: min-content;">
                    <el-row>
                        <el-col :span="markdownWeight" :style="{ 'margin-left': markdownLeft }"
                            style="transition: width 0.5s;">
                            <!-- 页面文章主体 -->
                            <div class="blog-main">
                                <!-- 文章标题及作者 -->
                                <div class="blog-main-top ">
                                    <!-- <el-button style="float: right; padding: 3px 0;width: 30px;height: 30px" @click="collectPartJob()" :type="collectType" icon="el-icon-star-off" circle>
                                    </el-button> -->

                                    <div class="main-titel">{{ article.title }}</div>
                                    <div class="author-info">
                                        <span class="el-icon-user"> 作 者：{{ article.nickName }}</span>
                                        <span class="el-icon-date"> 创建时间：{{ article.createTime }}</span>
                                        <span class="el-icon-view"> 浏 览 量：{{ article.pageView }}</span>
                                    </div>
                                </div>
                                <no-ssr>
                                    <!-- 文章内容 -->
                                    <mavon-editor v-model="article.content" defaultOpen="preview" :subfield="false"
                                        ref="markdown" id="markdown" :boxShadow="false" toolbarsBackground="#202124"
                                        previewBackground="#202124"></mavon-editor>
                                </no-ssr>
                                <!-- 文章评论 -->
                                <div class="comments">
                                    <div class="comments-top"><i class="el-icon-chat-line-round"></i>Comments</div>
                                    <div class="textarea-main">
                                        <el-input type="textarea" :rows="2" placeholder="你的评论....."
                                            v-model="blogComments.content" class="comments-center">
                                        </el-input>
                                        <div class="comments-button">
                                            <el-button @click="addComments()">评论</el-button>
                                        </div>
                                    </div>

                                    <!-- 评论头部 -->
                                    <div class="comments-bottom" id="comments-bottom">
                                        <div class="comments-bottom-titel">
                                            <el-row>
                                                <el-col :xs="6" :sm="10" :md="14" :lg="18" :xl="20">
                                                    <span class="text">{{ count }} 评论</span>
                                                </el-col>
                                                <el-col :xs="18" :sm="14" :md="10" :lg="6" :xl="4">
                                                    <!-- <span class="text1">按正序</span>
                                                    <span class="text1">按倒序</span>
                                                    <span class="text1">按热度</span> -->
                                                </el-col>
                                            </el-row>
                                            <el-row>
                                                <commentItem v-for="(c, index) in comments" :comment="c"
                                                    :articleId="article.id" :index="index"
                                                    :rootCommentCounts="comments.length"
                                                    @commentCountIncrement="commentCountIncrement"
                                                    @getArticleComments="getArticleComments" :key="c.id">
                                                </commentItem>
                                            </el-row>
                                        </div>
                                    </div>
                                </div>

                            </div>
                        </el-col>
                    </el-row>
                </el-main>

                <div class="right-eleme" :style="{ 'width': buttonWeight }">
                    <div class="catalog" v-show="isShow">
                        <div style="font-weight:bold; font-size: 20px; margin-left: 21%;">目录</div>
                        <el-tabs v-model='activeTab' tab-position="right" style="height: auto;"
                            @tab-click="handleClick">
                            <el-tab-pane :label="item.name" v-for="item in tocs" :key="item.href" :name="item.href">
                            </el-tab-pane>
                        </el-tabs>
                    </div>
                    <div class="right-button" id="right-button" :style="{ 'left': buttonLeft }">
                        <div class="shrink-button" @click="updateMarkDownWeight()">
                            <i :class="directoryIcon"></i>
                        </div>
                        <div class="shrink-button" @click="sendMsg()" style="margin: 10px 0;">
                            <i class="el-icon-message"></i>
                        </div>
                        <div class="review-button" @click="handleClickToComments()">
                            <i class="el-icon-chat-line-round"></i>
                        </div>
                        <div class="top-button" @click="handleClickToTop()" v-show="buttonShow">
                            <i class="el-icon-top"></i>
                        </div>
                    </div>
                </div>
            </el-container>
        </transition>
        <!-- <el-header>
            <BlogHeader/>
        </el-header>
        <el-footer style="height: 0;">
            <blog-footer></blog-footer>
        </el-footer> -->
    </el-container>
</template>

<script>
import BlogHeader from '~/pages/layouts/BlogHeader.vue';
import BlogFooter from '~/pages/layouts/BlogFooter.vue';
import articleApi from '~/api/article'
import commentItem from '~/pages/article/components/commentItem'
export default {
    components: { BlogHeader, BlogFooter, commentItem },
    data() {
        return {
            articleId: '',
            blogComments: {},
            article: {}, // 文章实体
            activeTab: '_0', // 目录高亮绑定值
            tocs: [], // 文章标题转目录的对象
            timer1: null,
            timer2: null,
            timer3: null,
            navList: [], // 标题标签列表
            scrollEnabled: true, // 用于控制，当点击目录时，关闭鼠标滚动监听
            markdownWeight: 20, // 文章所占的 el-col 宽度
            buttonWeight: 25,
            markdownFalg: true, // 控制文章宽度标识
            isShow: true, // 是否显示目录
            buttonLeft: '93%', // 侧边三个按钮的距离
            markdownLeft: '11%', // 文章的距离
            directoryIcon: 'el-icon-s-unfold', // 控制目录的 icon
            buttonShow: false, // 回到顶部的按钮的显示按钮
            comments: [],
            count: 0,
            collectType: ''
        }
    },
    async asyncData(context) {
        const articleId = context.route.query.articleId;
        return await articleApi.getArticleById(articleId).then(res => {
            return {
                article: res.data,
            }
        })
    },
    methods: {
        collectPartJob() { },
        sendMsg() {
            if (this.article.userId === this.$store.getters.userid) {
                this.$message.error("无法对自己发起私信！");
                return
            }
            this.$router.push({ path: "/chat/msg", query: { toUserId: this.article.userId } })
        },
        getArticleComments() {
            articleApi.getArticleComments(this.article.id).then(res => {
                this.comments = res.data.result
                this.count = res.data.count
            })
        },
        // 添加文章评论
        addComments() {
            this.blogComments.articleId = this.article.id
            this.blogComments.parentId = '0'
            articleApi.addArticleComments(this.blogComments).then(res => {
                this.$message.success("发布成功！")
                this.getArticleComments()
                this.blogComments.content = null;
            })
        },
        commentCountIncrement() {
            this.partJob.commentCount += 1
        },
        // 修改markdown的宽度
        updateMarkDownWeight() {
            if (this.markdownFalg) {
                this.directoryIcon = 'el-icon-s-fold'
                this.markdownWeight = 22;
                this.isShow = false
                this.markdownLeft = '8%'
                this.buttonLeft = '93%'
                this.buttonWeight = '10%'
                this.markdownFalg = false;
            } else {
                this.directoryIcon = 'el-icon-s-unfold'
                this.markdownWeight = 20;
                this.isShow = true
                this.buttonLeft = '93%'
                this.markdownLeft = '10%'
                this.buttonWeight = '25%'
                this.markdownFalg = true;
            }
        },
        // 点击目录跳转到对应文章标题处
        handleClick(tab, event) {
            this.scrollEnabled = false
            let element = document.getElementById(tab.$options.propsData.name);
            element.scrollIntoView({ behavior: "smooth" });
            this.timer3 = setTimeout(() => {
                this.scrollEnabled = true
            }, 2500)

        },
        // 跳转评论
        handleClickToComments() {
            let element = document.getElementById('comments-bottom')
            element.scrollIntoView({ behavior: "smooth" });
        },
        // 跳转顶部
        handleClickToTop() {
            let element = document.getElementById('container')
            element.scrollIntoView({ behavior: "smooth" });
        },
        /**
         * 这段代码的目的是选择页面中的所有标题，
         * 并为每个标题设置一个name属性和一个lev属性。
         * name属性的值为标题的文本内容，lev属性的值为标题的级别（从h1到h6转换为lev1到lev6）。
         */
        selectAllTitle() {
            let title = document.querySelectorAll("h1,h2,h3,h4,h5,h6");
            this.navList = Array.from(title);
            this.navList.forEach(item => {
                item.name = item.innerHTML
            })
            this.navList.forEach(el => {
                // 获取该元素的本地名称（localName），并找到名称中第一个字母为"h"的位置。
                let index = el.localName.indexOf('h');
                el.lev = 'lev' + el.localName.substring(index + 1, el.localName.length)
            });
        },

        // 解析文章中的a标签
        bulidMarkDown() {
            const aArr = this.$refs.markdown.$refs.vShowContent.querySelectorAll('a');
            let tocs = [];
            for (let i = 0; i < aArr.length; i++) {
                if (aArr[i].id) {
                    let href = aArr[i].id;
                    let name = aArr[i].parentNode.innerText;
                    tocs.push({
                        href,
                        name,
                    });
                }
            }
            this.tocs = tocs;
        },

        // 构建树状目录层级
        bulidTreeCatalog() {
            let navs = document.querySelectorAll('.el-tabs__item');
            for (let i = navs.length - 1; i >= 0; i--) {
                // 从lev1到lev6分别添加不同到样式
                document.querySelector('#' + navs[i].id).style.padding = "0";
                if (this.navList[i].lev == 'lev1') {
                    document.querySelector('#' + navs[i].id).style.paddingLeft = "10%";
                } else if (this.navList[i].lev == 'lev2') {
                    document.querySelector('#' + navs[i].id).style.paddingLeft = "20%";
                } else if (this.navList[i].lev == 'lev3') {
                    document.querySelector('#' + navs[i].id).style.paddingLeft = "30%";
                } else if (this.navList[i].lev == 'lev4') {
                    document.querySelector('#' + navs[i].id).style.paddingLeft = "40%";
                } else if (this.navList[i].lev == 'lev5') {
                    document.querySelector('#' + navs[i].id).style.paddingLeft = "50%";
                } else if (this.navList[i].lev == 'lev6') {
                    document.querySelector('#' + navs[i].id).style.paddingLeft = "60%";
                }
            }

        },
        // 监听鼠标滚动，目录跟随文章标题高亮
        handleScroll() {
            var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
            // 页面高度
            var documentHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
            // 到达底部直接让目录最后一个元素高亮
            var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            if ((windowHeight + scrollTop + 2) >= documentHeight) {
                this.activeTab = this.navList[this.navList.length - 1].children[0].id.toString();
                return;
            }
            if (scrollTop < 100) {
                this.buttonShow = false
            } else {
                this.buttonShow = true
            }
            if (this.scrollEnabled) {
                // 高亮跟随
                for (var i = 0; i < this.navList.length / 2; i++) {
                    var element = this.navList[i];
                    var elementTop = element.getBoundingClientRect().top;
                    if (elementTop > -100 && elementTop <= 10) {
                        this.activeTab = element.children[0].id.toString();
                        break
                    }
                }
            }
        },

    },
    created() {
        // this.articleId = this.route.query.articleId
        // this.getArticleById(this.route.query.articleId)
        this.getArticleComments()
    },
    async mounted() {
        // $nextTick 将回调延迟到下次DOM更新循环之后执行。在修改数据之后立即使用它,然后等待DOM更新。
        // 定时器用于解决服务段喧染，导致ref拿不到值的问题
        this.$nextTick(() => {
            // this.timer1 = setTimeout(() => {
            this.bulidMarkDown();
            this.selectAllTitle();
            // })

            this.timer2 = setTimeout(() => {
                this.bulidTreeCatalog()
            });

            window.addEventListener('scroll', this.handleScroll)
        });
        await this.$options.asyncData({ app: this.$app, error: this.$error, route: this.$route });
    },
    beforeDestroy() {
        window.removeEventListener('scroll', this.handleScroll)
        clearTimeout(this.timer1)
        clearTimeout(this.timer2)
        clearTimeout(this.timer3)
    }
}
</script>

<style scoped>
/* 修改代码块的主题色 */
/* 修改代码块的背景颜色 */
::v-deep .markdown-body blockquote {
    color: darkgrey;
    border-left: 0.25em solid;
}

::v-deep .hljs {
    color: #24292e;
    background: #f6f8fa;
}

::v-deep .markdown-body table tr {
    background-color: transparent !important;
}

.right-eleme {
    position: sticky;
    height: 100%;
    top: 70px;
    display: flex;
    align-items: baseline;
    width: 25%;
}

.comments-top {
    font-size: 1.38rem;
    color: #bebec6;
    margin: 20px 0 15px -10px;
    font-weight: 500;
    font-family: 'Times New Roman', Times, serif !important;
}

::v-deep .comments-top .el-icon-chat-line-round {
    font-weight: 900;
    font-size: 28px;
    margin-right: 5px;
}


.comments-bottom {
    width: 100%;
    /* height: 50px; */
    margin-top: 30px;
}

.comments-button {
    width: 100%;
    display: flex;
    justify-content: flex-end;
}

.text {
    color: #bebec6;
    font-size: 1.38rem;
    font-family: 'Noto Sans', 'Noto Sans SC', sans-serif;
    font-weight: 700;
}

.text1 {
    color: #666;
    font-size: 0.75em;
    float: right;
    margin-right: 10px;
    margin-top: 5px;
}


.comments {
    width: 95%;
    margin: 10px auto;

}

.comments-center {
    width: 98%;
}

.textarea-main {
    width: 100%;
    background-color: #1e1e1e;
    box-shadow: rgba(255, 255, 255, 0.05) 0px 6px 24px 0px, rgba(255, 255, 255, 0.08) 0px 0px 0px 1px !important;
    border: 1px solid rgba(255, 255, 255, 0.08);
    border-radius: 10px;
}

::v-deep .textarea-main .el-button {
    border-color: #a31f34;
    background: #a31f34;
    color: #000;
    width: 55.6px;
    height: 31.6px;
    text-align: center !important;
    line-height: 0 !important;
    padding: 0;
    margin-right: 2%;
    margin-bottom: 10px;
}

::v-deep .textarea-main .el-button:hover {
    border-color: #be243c;
    background: #be243c;
    color: #000;
    /* box-shadow: 0 4px 3px 1px #be243c, 0 6px 8px #be243c, 0 -4px 4px #be243c, 0 -6px 4px #be243c, inset 0 0 3px 3px #be243c; */

}

::v-deep .comments-center .el-textarea__inner {
    min-height: 150px !important;
}

::v-deep .comments .el-textarea__inner {
    /* min-height: 150px !important; */
    resize: none;
    overflow: hidden;
    margin: 15px 1.1%;
    color: white;
    background-color: #1e1e1e;
    border: none;
}

::v-deep .comments .el-textarea__inner:focus {
    background-color: #272727;
    transition: all 0.5s ease-in;
}

.main-titel {
    font-size: 3.2rem;
    font-weight: 700;
    margin: 10px 0px 30px 25px;
    line-height: 1.4;
    color: #cbcbd1;
    font-family: Satoshi-Variable, sans-serif, 'Noto Sans SC', sans-serif, 'Noto Sans SC', sans-serif;
}

.author-info {
    margin-left: 3%;
    color: #92929f;
}

.author-info span {
    margin-right: 20px;
}

.blog-main {
    box-shadow: rgba(255, 255, 255, 0.05) 0px 6px 24px 0px, rgba(255, 255, 255, 0.08) 0px 0px 0px 1px !important;
    background-color: #202124;
    width: 95%;
    margin: 10px 0 10px 2%;
    border-radius: 18px;
    padding: 10px;
}

.blog-main-top {
    height: 150px;
}

.right-button {
    position: fixed;
    margin-top: 2% !important;
    margin-top: 12px;
    color: #bebec6;
    font-size: 24px;
}

.shrink-button,
.review-button,
.top-button {
    height: 45px;
    width: 45px;
    border: none;
    text-align: center;
    line-height: 45px;
    border-radius: 10px;
    margin-bottom: 5px;
    box-shadow: rgba(255, 255, 255, 0.05) 0px 1px 4px 0px, rgba(255, 255, 255, 0.08) 0px 0px 0px 1px !important;
}

.top-button {
    margin-top: 900%;
}

.shrink-button:hover,
.review-button:hover,
.top-button:hover {
    background-color: #a31f34;
    color: black;
}

::v-deep .el-tabs__active-bar {
    background-color: #a31f34;
}

::v-deep .el-tabs__item.is-active {
    color: #a31f34;
}

.el-header {
    padding: 0;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 9999;
}


::v-deep .el-tabs__content {
    display: none;
}

.el-header,
.el-footer {
    padding: 0;
}

::v-deep .el-tabs--right .el-tabs__nav-wrap.is-right {
    margin-top: 20px;
    margin-left: -170px;
}

.el-col {
    overflow: auto
}

.catalog {
    position: fixed;
    margin-top: 2%;
    /* background-color: #202124; */
    color: #cbcbd1;
    width: 220px;
    height: 100%;
    transition: opacity 0.5s;
}

.markdown-body {
    transition: width .2s ease;
    box-sizing: border-box;
    background: #202124;
    color: #cbcbd1;
    border: none;
    box-shadow: none !important;


}

.markdown-body:hover {
    box-shadow: 0 0 10px 0 #7d8ea4 inset;
}

::v-deep .markdown-body h1,
::v-deep .markdown-body h2 {
    border-bottom: none !important
}

::v-deep .v-note-op {
    display: none !important;
    color: #cbcbd1;
}

::v-deep .el-tabs__item {
    color: #cbcbd1;
}
</style>